from .models import ShopCar
from rest_framework import serializers
from rest_framework.exceptions import APIException
from goods.models import GoodsShelf


class ShopCarSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShopCar
        fields = [
            'id',
            'style',
            'buy_num',
            'goods_info',
            'orders',
            'goods',
            'user_id',
            'user',
        ]
        extra_kwargs = {
            'orders': {'write_only': True},
            'goods': {'write_only': True},
            'user': {'write_only': True}
        }


class UpdateCarSerializer(serializers.ModelSerializer):
    shop_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = ShopCar
        fields = ['buy_num', 'shop_id']
        extra_kwargs = {
            'buy_num': {'write_only': True},
        }

    def update(self, instance, validated_data):
        buy_num = validated_data.get('buy_num')
        shop_id = validated_data.get('shop_id')
        goods_obj = GoodsShelf.objects.filter(id=shop_id).first()
        if buy_num > goods_obj.stock_num:
            raise APIException('库存告急,请联系管理员')
        else:
            instance.buy_num = buy_num
            instance.save()
            return instance
